import { $getChooseList, $piccInvoiceCreate } from "@/api/userCenter/applyInvoice/applyInvoice";
import { message } from "ant-design-vue";
import { computed, defineComponent, onMounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import styles from "./applyInvoice.module.less";
import dayjs from 'dayjs';

export default defineComponent({
  name:'userCenterApplyInvoice',
  setup() {
    const router = useRouter();
    const searchForm = reactive({
      channel: 0,   //渠道
      product_name: null, //保险产品
      create_start_time: null,//投保时间
      create_end_time: null,
      InvoiceHeader: null,   //投保人姓名
      time: [],
    })
    const channels = ref([
      {
        text: '在线开票',
        value: 0,
      },
    ])

    //点击查询
    const clickSearch = () => {
      getList();
    }
    //重置
    const reset = () => {
      searchForm.product_name = null;
      searchForm.InvoiceHeader = null;
      searchForm.time = [];
    }
    //时间change
    const timeChange = () => {
      if (searchForm.time === null) {
        searchForm.time = [];
      }
    }
    //筛选查询
    const Search = () => (
      <div class={styles['search-box']}>
        <div class={styles.title}>搜索查询</div>
        <div class={styles['form-row']}>
          <div class={styles['form-item']}>
            <div class={styles['form-item-label']}>保险产品：</div>
            <a-input style="width:60%" placeholder="请输入保险产品" v-model:value={searchForm.product_name}></a-input>
          </div>
          <div class={styles['form-item']}>
            <div class={styles['form-item-label']}>投保人姓名：</div>
            <a-input style="width:60%" placeholder="请输入投保人姓名" v-model:value={searchForm.InvoiceHeader}></a-input>
          </div>
        </div>
        <div class={styles['form-row']}>
          <div class={styles['form-item']}>
            <div class={styles['form-item-label']}>提交时间：</div>
            <a-range-picker v-model:value={[searchForm.time]} valueFormat="YYYY-MM-DD" style="margin-left: 10px;" onChange={() => { timeChange() }}></a-range-picker>
          </div>
        </div>
        <div class={styles['search-row']}>
          <div class={[styles['searchBtn'], styles.plain]} onClick={() => { reset() }}>重置</div>
          <div class={styles['searchBtn']} onClick={() => { clickSearch() }}>查询</div>
        </div>
      </div>
    )
    const invoice = reactive({
      invoiceNum: 0,
      form: {
        invoiceType: 1,  //发票类型
        contacts: '',    //发票抬头
        phone: '',   //电话
        address_and_phone: '',   //地址手机号
        title: '', //发票抬头
        email: '', //邮箱
        buyer_tax_no: '', //购买方纳税人识别号
        bank_account: '', //银行账户
      },
      tips_show: false,
      invoiceTypes: [
        {
          label: '短链接下载',
          value: 1,
        },
        {
          label: '版式下载',
          value: 2,
        },
      ],
    } as any)
    const blurHandler = () => {
      if (!invoice.form.invoiceType) {
        invoice.tips_show = true
      } else {
        invoice.tips_show = false
      }
    }
    //发票
    const Invoice = () => (
      <div class={styles['invoice-box']}>
        <div class={styles['invoice-box-tips']}>当前共有 {invoice.invoiceNum || 0} 张保单可开具发票。</div>
        <div class={styles['invoice-form']}>
          <div class={styles['invoice-form-row']}>
            <div class={styles['invoice-form-item']}>
              <div class={styles['form-item-label']}>
                <span>开票渠道：</span>
              </div>
              <div class={styles['form-item-value']}>在线开票</div>
            </div>
            <div class={styles['invoice-form-item']}>
              <div class={styles['form-item-label']}>
                <span>发票类型：</span>
              </div>
              <div class={styles['form-item-value']}>电子发票</div>
            </div>
          </div>
          <div class={styles['invoice-form-row']}>
            <div class={styles['invoice-form-item']}>
              <div class={styles['form-item-label']}>
                <span>发票获取方式:</span>
              </div>
              <a-select
                v-model={[invoice.form.invoiceType, "value"]}
                options={invoice.invoiceTypes}
                style="width:50%;height:40px;"
                allowClear={true}
              >
              </a-select>
              {/* <span class={[styles.tips, invoice.tips_show && styles.showTips]}>请输入发票类型</span> */}
            </div>
            <div class={styles['invoice-form-item']}>
              <div class={styles['form-item-label']}>
                <span class={styles['tips-icon']}>*</span>
                <span>发票抬头:</span>
              </div>
              <a-input style="width:50%" placeholder="请输入发票抬头" v-model:value={invoice.form.contacts}></a-input>
            </div>
          </div>
          <div class={styles['invoice-form-row']}>
            <div class={styles['invoice-form-item']}>
              <div class={styles['form-item-label']}>
                <span class={styles['tips-icon']}>*</span>
                <span>邮箱:</span>
              </div>
              <a-input style="width:50%" placeholder="请输入邮箱" v-model:value={invoice.form.email}></a-input>
            </div>
            <div class={styles['invoice-form-item']}>
              <div class={styles['form-item-label']}>
                <span class={styles['tips-icon']}>*</span>
                <span>联系人手机号:</span>
              </div>
              <a-input style="width:50%;" placeholder="请输入联系人手机号" v-model:value={invoice.form.phone}></a-input>
            </div>
          </div>
          <div class={styles['invoice-form-row']}>
            <div class={styles['invoice-form-item']}>
              <div class={styles['form-item-label']}>
                <span>购买方纳税人识别号:</span>
              </div>
              <a-input style="width:50%" placeholder="请输入" v-model:value={invoice.form.buyer_tax_no}></a-input>
            </div>
            <div class={styles['invoice-form-item']}>
              <div class={styles['form-item-label']}>
                <span>银行账户:</span>
              </div>
              <a-input style="width:50%;" placeholder="请输入银行账户" v-model:value={invoice.form.bank_account}></a-input>
            </div>
          </div>
          <div class={styles['form-address']}>
            <span>地址和手机号：</span>
            <a-input style="width:80%;" placeholder="请输入地址和手机号" v-model:value={invoice.form.address_and_phone}></a-input>
          </div>
        </div>
      </div>
    )
    const invoiceTable = reactive({
      columns: [
        {
          title: "ID",
          dataIndex: "id",
          align: "center",
          width: "20px",
        },
        {
          title: "产品名称",
          dataIndex: "name",
          align: "center",
          width: "250px",
        },
        {
          title: "保单号",
          dataIndex: "policy_no",
          align: "center",
          width: "150px",
        },
        {
          title: "投保人姓名",
          dataIndex: "applicant_name",
          align: "center",
          width: "200px",
        },
        {
          title: "提交时间",
          dataIndex: "create_time",
          align: "center",
          width: "180px",
        },
        {
          title: "投保期间",
          dataIndex: "data",
          align: "center",
          width: "240px",
        },
        {
          title: "保费",
          dataIndex: "sum_premium",
          align: "center",
          width: "80px",
        },
      ],
      dataSource: [],
      selectedRowKeys: [],  //当前页选中项
      selectedRows: [],  //已选中项
      total: 24,
      pagination: {
        total: 1,
        current: 1,
        pageSize: 10,
      },
      loading: false,
    } as any);

    //选中项变更
    const onSelectChange = (changableRowKeys: any[]) => {
      invoiceTable.selectedRowKeys = changableRowKeys;
    };
    //用户手动选择/取消选择某列的回调
    const onSelect = (record: any, selected: boolean, selectedRows: any[]) => {
      if (selected) { //选择
        invoiceTable.selectedRows = [...new Set([...selectedRows.map((item: any) => item.policy_no), ...invoiceTable.selectedRows])]
        console.log(invoiceTable.selectedRows)
      } else {  //取消选择
        console.log('record', record.policy_no)
        invoiceTable.selectedRows = invoiceTable.selectedRows.filter((item: any) => item !== record.policy_no);
        console.log(invoiceTable.selectedRows)
      }
    }
    const rowSelection = computed(() => {
      return {
        selectedRowKeys: invoiceTable.selectedRowKeys,
        fixed: true,
        onChange: onSelectChange,
        onSelect: onSelect,
      }
    })

    // 表格状态变更
    const tableChangeHandler = (pag: { pageSize: number; current: number }) => {
      invoiceTable.pagination.current = pag.current;
      invoiceTable.pagination.pageSize = pag.pageSize;
      getList();
      const dom: any = document.getElementById("app");
      console.log(dom.scrollTop);
      // dom.scrollTop = 280;
    };


    //获取保单列表
    const getList = () => {
      invoiceTable.loading = true;
      $getChooseList({
        pro_name:searchForm.product_name || undefined,
        applicant_name:searchForm.InvoiceHeader || undefined,
        create_start_time: searchForm.time.length > 0 ? String((new Date(searchForm.time[0]).getTime() / 1000).toFixed(0)) : undefined,
        create_end_time: searchForm.time.length > 0 ? String((new Date(searchForm.time[1]).getTime() / 1000).toFixed(0)) : undefined,
        page: invoiceTable.pagination.current,
        limit: invoiceTable.pagination.pageSize,
      }).then((res: any) => {
        invoiceTable.loading = false;
        invoiceTable.dataSource = res.data?.data || [];
        invoiceTable.pagination.total = res.data?.total || '';
        invoiceTable.pagination.current = res.data?.current_page || '';
        invoiceTable.pagination.pageSize = res?.data?.per_page || '';
        invoice.invoiceNum = res.data.total;
        invoiceTable.selectedRowKeys = res.data?.data?.filter((item: any) => invoiceTable.selectedRows.includes(item.policy_no)).map((item: any) => item.policy_no)
        console.log(invoiceTable.selectedRows)
      }).catch(() => {
        invoiceTable.loading = false;
      })
    }

    onMounted(() => {
      getList();
    })

    const invoiceBtn = ref('开票申请');
    const isClick = ref(false as any);
    //开票
    const invoiceCreate = () => {
      console.log(invoiceTable.selectedRows)
      console.log(invoiceTable.selectedRowKeys.length)
      if (invoiceTable.selectedRowKeys.length === 0) {
        message.error('请选择需要开票的保单');
        return;
      }
      if (!invoice.form.invoiceType) {
        message.error('请选择发票获取方式');
        return;
      }
      if (!invoice.form.contacts) {
        message.error('发票抬头不能为空');
        return;
      }
      if (!invoice.form.email) {
        message.error('邮箱不能为空');
        return;
      }
      if (!invoice.form.email) {
        message.error('联系人手机号不能为空');
        return;
      }
      if (invoiceTable.selectedRowKeys.length >= 2 && !invoice.form.buyer_tax_no) {
        message.error('购买方纳税人识别号不能为空');
        return;
      }
      if (invoiceTable.selectedRowKeys.length >= 2 && !invoice.form.bank_account) {
        message.error('银行账户不能为空');
        return;
      }
      if (invoiceTable.selectedRowKeys.length >= 2 && !invoice.form.address_and_phone) {
        message.error('地址和手机号不能为空');
        return;
      }
      if (isClick.value === true) return;
      isClick.value = true;
      invoiceBtn.value = '开票中'
      $piccInvoiceCreate({
        title: invoice.form.contacts,
        phone: invoice.form.phone,
        email: invoice.form.email,
        policy_no: invoiceTable.selectedRows,
        address_and_phone: invoice.form.address_and_phone,
        buyer_tax_no: invoice.form.buyer_tax_no,
        bank_account: invoice.form.bank_account,
        download_type: invoice.form.invoiceType,
      }).then((res: any) => {
        message.success('开票成功')
        const dom: any = document.getElementById("app");
        dom.scrollTop = 0;
        router.push('/userCenter/invoiceHistory')
        isClick.value = false;
      }).catch(() => {
        isClick.value = false;
        invoiceBtn.value = '开票申请';
      })
    }
    //发票申请
    const InvoiceTable = () => (
      <div class={styles.invoiceTable}>
        <a-table
          columns={invoiceTable.columns}
          bordered={true}
          scroll={{ x: "max-content" }}
          onChange={tableChangeHandler}
          dataSource={invoiceTable.dataSource}
          row-selection={rowSelection.value}
          rowKey="policy_no"
          pagination={invoiceTable.pagination}
          loading={invoiceTable.loading}
          v-slots={{
            bodyCell: ({ column, record }: any) => {
              // 产品名称
              if (column.dataIndex === "name") {
                return record.name + record.plan_name
              }
              //投保期间
              if (column.dataIndex === "data") {
                return record.start_date + '至' + record.end_date
              }
            },
          }}
        />
        <div class={styles.operation}>
          <div class={styles.btn} onClick={() => { invoiceCreate() }}>{invoiceBtn.value}</div>
        </div>
      </div>
    )

    return () => (
      <div class={styles.applyInvoice}>
        <div class={styles['header-box']}>
          <span>申请开票</span>
        </div>
        <Invoice />
        <Search />
        <InvoiceTable />
      </div>
    )
  }
})